package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.AttendanceResponse;
import com.ycsj.goldmedalnewconcept.bean.AttendanceSave;
import com.ycsj.goldmedalnewconcept.bean.StudentAttendance;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;
import com.ycsj.goldmedalnewconcept.view.ChangeDatePopwindow;
import com.ycsj.goldmedalnewconcept.R;

//考勤管理
public class AttendanceActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private ListView lv_attend;
	private List<StudentAttendance> list1 = new ArrayList<StudentAttendance>();
	private MyAdapter mAdapter;
	private TextView selectDate;
	private TextView tv_calender;
	private TextView tv_save;
	private String year;
	private String month;
	private String day;
	private String attendance_date;
	private String class_id;
	private String account;
	private String role;
	private String listString;
	private Intent intent;
	private Handler handler;
	TimePickerView pvTime;
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_attendance);
		handler = new MyHandler();
		intent = getIntent();
		class_id = intent.getStringExtra("class_id");
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		
		attendance_date = TimeUtil.getYearMonthDay();
		initView();
		setOnListener();
		initData();
	}

	private void initView() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		lv_attend = (ListView) findViewById(R.id.lv_attend);
		selectDate = (TextView) findViewById(R.id.startDate1);
		selectDate.setText(attendance_date);
		tv_save = (TextView) findViewById(R.id.tv_save);
		tv_calender = (TextView) findViewById(R.id.tv_calender);

	}

	private void initData() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "18");
//		builder.add("c", "15333838051");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("user_class", class_id);
		builder.add("attendance_date", attendance_date);
		// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=18&c=15333838051&role=2&user_class=1&attendance_date=2017-06-01
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL+"ManageMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				AttendanceResponse fromJson = gson.fromJson(json,
						AttendanceResponse.class);

				Message message = Message.obtain();
				message.arg1 = 0;
				message.obj = fromJson;
				handler.sendMessage(message);
			}
		});
	}

	public class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			AttendanceResponse fromJson = (AttendanceResponse) msg.obj;
			if (fromJson == null) {
				Toast.makeText(getApplicationContext(), "错误，请检查网络是否正常", 0)
						.show();
				return;
			}

			if (fromJson.list != null) {
				mAdapter = new MyAdapter(getBaseContext(), fromJson.list);
				list1 = new ArrayList<StudentAttendance>();
				StudentAttendance sa = new StudentAttendance();

				for (int i = 0; i < fromJson.list.size(); i++) {
					list1.add(sa);
				}

				for (int i = 0; i < fromJson.list.size(); i++) {

					list1.get(i).ATTENDANCE_TYPE = fromJson.list.get(i).ATTENDANCE_TYPE;
					list1.get(i).name = fromJson.list.get(i).name;
					list1.get(i).sttel = fromJson.list.get(i).sttel;
				}
				lv_attend.setAdapter(mAdapter);
			}
		}
	}

	private void setOnListener() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		selectDate.setOnClickListener(this);
		tv_calender.setOnClickListener(this);
//		selectDate2.setOnClickListener(this);
//		selectDate3.setOnClickListener(this);
		tv_save.setOnClickListener(this);
	}

	class ViewHolder {
		public TextView tv_name;
		public RadioButton rb1;
		public RadioButton rb2;
		public RadioButton rb3;
		public RadioButton rb4;
		public RadioGroup rg;
	}

	class MyAdapter extends BaseAdapter {
		List<StudentAttendance> list;
		private LayoutInflater mInflater = null;

		private MyAdapter(Context context, List list) {

			this.mInflater = LayoutInflater.from(context);
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.list_attendance, null);
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tv_name);
				holder.rb1 = (RadioButton) convertView.findViewById(R.id.rb1);
				holder.rb2 = (RadioButton) convertView.findViewById(R.id.rb2);
				holder.rb3 = (RadioButton) convertView.findViewById(R.id.rb3);
				holder.rb4 = (RadioButton) convertView.findViewById(R.id.rb4);
				holder.rg = (RadioGroup) convertView.findViewById(R.id.rg);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.tv_name.setText(list.get(position).name);
			String TYPE = list.get(position).ATTENDANCE_TYPE;
			holder.rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(RadioGroup group, int checkedId) {

					switch (checkedId) {
					case R.id.rb1:
						StudentAttendance st1 = new StudentAttendance();
						st1.ATTENDANCE_TYPE = "0";
						st1.name = list.get(position).name;
						st1.sttel = list.get(position).sttel;
						list1.set(position, st1);
						break;
					case R.id.rb2:
						StudentAttendance st2 = new StudentAttendance();
						st2.ATTENDANCE_TYPE = "1";
						st2.name = list.get(position).name;
						st2.sttel = list.get(position).sttel;
						list1.set(position, st2);
						break;
					case R.id.rb3:
						StudentAttendance st3 = new StudentAttendance();
						st3.ATTENDANCE_TYPE = "2";
						st3.name = list.get(position).name;
						st3.sttel = list.get(position).sttel;
						list1.set(position, st3);
						break;
					case R.id.rb4:
						StudentAttendance st4 = new StudentAttendance();
						st4.ATTENDANCE_TYPE = "3";
						st4.name = list.get(position).name;
						st4.sttel = list.get(position).sttel;
						list1.set(position, st4);
						break;
					default:
						break;
					}
				}

			});
			if (TYPE == null) {
				TYPE = "0";
			}

			switch (Integer.parseInt(TYPE)) {
			case 0:
				holder.rb1.setChecked(true);
				break;
			case 1:
				holder.rb2.setChecked(true);
				break;
			case 2:
				holder.rb3.setChecked(true);
				break;
			case 3:
				holder.rb4.setChecked(true);
				break;

			default:
				break;
			}

			return convertView;
		}
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_calender:
		case R.id.startDate1:
			pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
			pvTime.setTime(new Date());
			pvTime.setCyclic(false);
			pvTime.setCancelable(true);
			pvTime.show();
			// 时间选择后回调
			pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener(){

				@Override
				public void onTimeSelect(Date date){
//					updateUserinfo("日期",getTime(date));
//					tv_user_birthday.setText(getTime(date));
					attendance_date = getTime(date);
					Log.e("time", attendance_date);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							selectDate.setText(attendance_date);
						}
					});
					initData();
				}

				public String getTime(Date date){
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				return format.format(date);
			}

			});
			
			break;
		case R.id.tv_save:
			tv_save.setClickable(false);
			save();
			break;
		}
	}

	
	
	
	
	
	
	
	
	
	
	
	// 保存
	private void save() {
		Toast.makeText(getBaseContext(), "正在上传，请耐心等待", 0).show();
		Gson gson = new Gson();
		AttendanceSave att = new AttendanceSave();
		att.list = list1;
		listString = gson.toJson(att);
//		Log.e("test", listString);

		OkHttpClient mOkHttpClient = new OkHttpClient();
		//mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "17");
//		builder.add("c", "15333838051");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("attendance_date", attendance_date);
		builder.add("list", listString);
		builder.add("user_class", class_id);
		// type=17/c/role/attendance_date/list
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL+"ManageMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						tv_save.setClickable(true);
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
						Log.e("test", "fail");
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息
				tv_save.setClickable(true);
				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				AttResponse fromJson = gson.fromJson(json, AttResponse.class);
				if (fromJson != null) {
					if ("1".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(getBaseContext(), "保存成功", 0)
										.show();
							}
						});
					} else {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(getBaseContext(),
										"保存失败，请检查网络连接是否正常", 0).show();
							}
						});
					}
				}
			}
		});
	}
}
